package net.maku.framework.security.filter;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.constant.MessageConstant;
import net.maku.framework.security.cache.TokenStoreCache;
import net.maku.framework.security.user.UserDetail;
import net.maku.framework.security.utils.ThreadLocalUtil;
import net.maku.framework.security.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * kyy应用认证过滤器
 */
@Component
@AllArgsConstructor
public class KyyAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenStoreCache tokenStoreCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 从请求头中获取 Token
        String accessToken = TokenUtils.getAccessToken(request);
        // 如果 Token 为空，直接放行请求
        if (StrUtil.isBlank(accessToken)) {
            chain.doFilter(request, response);
            //请先登录
//            throw new ServletException(MessageConstant.PLEASE_LOGIN);
            return;
        }

        //根据token获取用户信息
        UserDetail kyyUser = tokenStoreCache.getKyyUser(accessToken);
        //如果用户信息为空，直接放行请求
        if (kyyUser == null) {
            chain.doFilter(request, response);
            //请先登录
//            throw new ServletException(MessageConstant.PLEASE_LOGIN);
            return;
        }
        // 检查用户是不是管理端用户
        if (kyyUser.getUserType()== Constant.Manage_TYPE) {
            chain.doFilter(request, response);
            return;
        }

        // 创建认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(kyyUser, null, kyyUser.getAuthorities());
        // 创建并设置 SecurityContext
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        Map<String,Object> map=new HashMap<>();
        map.put(Constant.KYY_USER_ID,kyyUser.getId());
        ThreadLocalUtil.set(map);
        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}
